package org.example.ymcc.util;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(value = "ali.pay")
public class AliPayUtil {
    private String appId;
    private String gatewayHost;
    private String merchantPrivateKey;
    private String alipayPublicKey;

    public String toPay(String title,String orderNo,String amount,String returnUrl){
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());
        try {
            // 2. 发起API调用（以创建当面付收款二维码为例）
            AlipayTradePagePayResponse pay = Factory.Payment.Page()
                    .pay(title, orderNo, amount, returnUrl);
            // 3. 处理响应或异常
            return pay.getBody();
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private Config getOptions() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = this.gatewayHost;//正式地址
        config.signType = "RSA2";
        config.appId = this.appId;
        config.merchantPrivateKey = this.merchantPrivateKey;
        config.alipayPublicKey = this.alipayPublicKey;
        config.notifyUrl = "http://aenbm2.natappfree.cc/ymcc/pay/payOrder/callback";
        return config;
    }
}
